import React, {Component} from 'react'
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ListView,
  Dimensions,
  ScrollView, FlatList, TextInput
} from 'react-native'
import Toast2, {
  DURATION
} from 'react-native-easy-toast'
import {Toast, Overlay, Label, Input} from 'teaset'
import font from './../../styles/font'
import string from './../../utils/srting'
import {Actions} from "react-native-router-flux";
import { SafeAreaView } from 'react-navigation';
import DateTimePicker from "react-native-modal-datetime-picker";
import * as String from './../../utils/srting'

const {
  height: deviceHeight,
  width: deviceWidth
} = Dimensions.get("window");

class UserOrderScene extends Component{
  constructor(props){
    super(props)

    this.state = {
      dataSource: [],
      number: '',
      findOrder: 0,
      isDateTimePickerVisible: false,
      dateTime:'请选择丢失订单 创建时间'
    }
  }

  componentDidMount() {
    this.props.actions.getUserOrder()
  }


  componentWillReceiveProps(nextProps) {
    const {
      userOrder,
      orderSubmit
    } = nextProps;

      if(this.props.userOrder !== userOrder) {
        if (userOrder.error !== false) {
          if (userOrder.error.status === 401) {
            Actions.login()
            return;
          }
          this.toast.show(userOrder.error.message)
        } else {
          if (userOrder.data && userOrder.data.length > 0) {
            this._setRows(userOrder.data);
            this.setState({
              dataSource: this._getRows(),
            });
          }
        }
      }

    if(this.props.orderSubmit !== orderSubmit) {
      if (orderSubmit.error !== false) {
        if (orderSubmit.error.status === 401) {
          Actions.login()
          return;
        }
        this.toast.show(orderSubmit.error.message)
      } else {
        if (orderSubmit.data && !orderSubmit.isLoading) {
          this.setState({'number': ''})
          this.customPopView && this.customPopView.close()
          if(orderSubmit.data === '订单已领取过,请换个订单号再领'){
            Toast.fail(orderSubmit.data)
          }else{
            this.setState({'number': ''})
            this.props.actions.getUserOrder()
            Toast.success(orderSubmit.data)
          }
        }
      }
    }
    }

  _setRows(rows) {
    this._rows = rows;
  }
  _getRows() {
    return this._rows ? this._rows : [];
  }


  _submit(){
    if(this.state.number === ''){
      Toast.fail('请输入订单号')
    }else{
      this.props.actions.orderSubmit({number: this.state.number})
    }
  }


  showDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: true });
  };

  hideDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: false });
  };

  handleDatePicked = date => {
    // console.log(String.formatDateTime(date))
    this.setState({dateTime: String.formatDateTime(date)})
    this.hideDateTimePicker();
  };



  renderSubmitOverlay(){
    return(
        <Overlay.PopView
          style={{alignItems: 'center', paddingTop:80}}
          ref={v => this.customPopView = v}
        >
            <View style={styles.overlayContainer}>

              <Text style={[font.black18, {marginTop:20, marginBottom:5}]}>请输入订单号</Text>
              <Text style={{fontSize:14, color:'#999'}}>您购买的商品订单号进行积分领取</Text>
              <Input
                keyboardType='numeric' style={{width: 180, marginVertical:10}}
                onChangeText={(data)=>{this.setState({number: data})}}
                placeholder='请输入订单号'
              />
              <View style={styles.button}>
                <TouchableOpacity style={[styles.buttonItem]} onPress={()=>{
                  this.customPopView && this.customPopView.close()
                }}>
                  <Text style={{color:'#5f646e'}}>取消</Text>
                </TouchableOpacity>
                <View style={{height:40, borderLeftWidth: 1,borderLeftColor:'#d5d5d6'}}></View>
                <TouchableOpacity style={styles.buttonItem} onPress={()=>{
                  this._submit()
                }}>
                  <Text style={{color:'#3cc51f'}}>确定</Text>
                </TouchableOpacity>
              </View>
            </View>
        </Overlay.PopView>
    )
  }

  //查找订单
  findOrder(){
    let mydata = this.state.dateTime
    let url = 'https://tao.vyxjj.com/index/index/auto_order';
    // let body = {action:'yes', lost:mydata}

    let formData = new FormData();

    formData.append('action', 'yes');
    formData.append('lost', mydata);

    fetch(url,{
      method: 'POST',
      body: formData
    }).then(function (res) {
      return res.text()
    }).then(function (result) {
      if(result != ''){
        this.props.actions.getUserOrder()
        Toast.success('订单找回成功!')
      }else{
        Toast.fail('没有找到丢失订单!')
      }
    }.bind(this)).done()
  }


  renderRow(orders){
    let order = orders.item
    if(order.status === '完成订单'){
      return(
        <View style={styles.item}>
          <Text style={[{fontSize:15, marginBottom:8, color:'#000'}]}>{order.number}</Text>
          <Text style={[{fontSize:14, marginBottom:8, color:'#E12F32', lineHeight:20}]}>{order.title}</Text>
          <View style={{flex:1, flexDirection:'row', marginBottom:8}}>
            <Text style={{color:'#000', fontSize:13, marginRight:20}}>支付：
              <Text style={{color:'#f00', fontSize:13}}>￥{order.jiage}</Text>
            </Text>
            <Text style={{color:'#000', fontSize:13, marginRight:20}}>平台返利：
              <Text style={{color:'#f00', fontSize:13}}>{order.price}元</Text>
            </Text>
          </View>
          <Text style={{color:'#999', fontSize:13, marginBottom:8}}>状态：
            {order.orderStatus == '订单付款' ?
              <Text style={{marginLeft: 5, color:'red', fontSize:13}}>{order.orderStatus}</Text>
              :
              <Text style={{marginLeft: 5, color:'green', fontSize:13}}>{order.orderStatus}</Text>
            }

          </Text>
          <Text style={{color:'#999', fontSize:13}}>订单创建时间：{order.created_at}</Text>
        </View>
      )
    }else{
      return null;
    }

  }

  ListHeaderComponent(){
    return(
      <View style={styles.headerContainer}>
        <Text style={{color:'#fff', fontSize:20,}}>订单手动找回</Text>
        <View style={styles.findOrder}>
          <Input
            keyboardType='numeric' style={{width: 230, marginVertical:10, borderWidth: 0}}
            onChangeText={(data)=>{this.setState({number: data})}}
            placeholder='请输入订单号'
            value={this.state.number}
          />
          <TouchableOpacity style={styles.findOrderBut} activeOpacity={1} onPress={()=>{this._submit()}}>
            <Text style={{color:'#E12F32', fontSize:14, textAlign: 'center'}}>找回订单</Text>
          </TouchableOpacity>
        </View>
        <Text style={{color:'#fff', fontSize:13}}>如果没有您的订单，请复制淘宝订单创建时间进行找回。</Text>
      </View>
    )
  }

  ListEmptyComponent(){
    return(
      <View style={{height:300, justifyContent:'center', alignItems:'center'}}>
        <Text>没有记录哦~</Text>
      </View>
    )
  }

  render(){
    return(
      <SafeAreaView style={styles.container}>
        <FlatList
          ref={(view) => { this.myFlatList = view; }}
          data={this.state.dataSource}
          ListHeaderComponent={this.ListHeaderComponent()}
          renderItem={this.renderRow.bind(this)}
          nestedScrollEnabled={true}
          ListEmptyComponent={this.ListEmptyComponent.bind(this)}
          // enableEmptySections={true}
          // style={styles.lists}
        />
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this.handleDatePicked}
          onCancel={this.hideDateTimePicker}
          cancelTextIOS='取消'
          confirmTextIOS='确认'
          titleIOS='选择时间'
          mode='datetime'
        />
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  container:{
    flex:1,
    backgroundColor:'#fff'
  },
  title:{
    color:'#999',
    fontSize:13,
  },
  submit:{
    marginVertical:15,
    backgroundColor:'#f00',
    borderRadius:5,
    justifyContent:'center',
    alignItems:'center',
    height:40
  },
  item:{
    borderBottomColor:'#e5e5e5',
    borderBottomWidth:0.3,
    paddingBottom:20,
    marginLeft: 15,
    marginTop:15,
    marginRight:10,
  },
  overlayContainer:{
    width: deviceWidth * 0.8,
    maxWidth: 300,
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'#fff',
    borderRadius:5,
    height:160
  },
  button:{
    borderTopWidth:0.3,
    borderTopColor:'#d5d5d6',
    flex:1,
    flexDirection:'row',
    justifyContent:'space-around',
    alignItems:'center',
    height:40,
  },
  buttonItem:{
    flex:1,
    justifyContent:'center',
    alignItems:'center',
    height:40,
  },
  headerContainer:{
    backgroundColor: '#E12F32',
    paddingHorizontal:15,
    paddingTop: 20,
    flex:1,
    flexDirection:'column',
    height:150,

  },
  findOrder:{
    backgroundColor:'#fff',
    flexDirection:'row',
    paddingVertical: 10,
    paddingLeft:15,
    borderRadius:15,
    marginTop: 15,
    alignItems:'center',
    height:45,
    justifyContent:'space-between',
    marginBottom:15
  },
  findOrderBut:{
    height:45,
    borderLeftWidth: 1,
    borderLeftColor:'#E12F32',
    justifyContent:'center',
    alignItems:'center',
    // flex:1,
    width:80,
  }
})

export const LayoutComponent = UserOrderScene

export function mapStateToProps(state, props) {
  return {
    routes: state.routes,
    userOrder: state.userOrderReducer,
    orderSubmit: state.orderSubmitReducer
  }
}